//
//  NSString+Commons.m
//  Categorys
//
//  Created by taihankeji on 2017/5/17.
//  Copyright © 2017年 taihankeji. All rights reserved.
//

#import "NSString+Commons.h"
#import "CommonCrypto/CommonDigest.h"


@implementation NSString (Commons)

- (NSString *)getMd5String {
    const char *cstr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cstr, (CC_LONG)strlen(cstr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (BOOL)isContainsString:(NSString *)string {
    if ([self rangeOfString:string].location != NSNotFound) {
        
        return YES;
        
    }else {
        return NO;
    }
}

- (CGSize)stringSizeWithFont:(UIFont *)font {
    return [self sizeWithAttributes:@{NSFontAttributeName:font}];
}

- (BOOL)isBlankString {
    
    if (self == nil || self == NULL) {
        return YES;
    }
    
    if ([self isKindOfClass:[NSNull class]]) {
        return YES;
    }
    
    if ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        return YES;
    }
    return NO;
}

- (NSDictionary *)jsonStringToDictionary {
    NSError *errorJson;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&errorJson];
    if (errorJson != nil) {
#ifdef DEBUG
        NSLog(@"fail to get dictioanry from JSON: %@, error: %@", self, errorJson);
#endif
    }
    return jsonDic;
}

- (NSDictionary *)xmlStribgToDictionary {
    return nil;
}

- (NSDictionary *)urlStrinToDictionary {
    //判断URL中是否存在参数
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    // 以字典形式将参数返回
    NSMutableDictionary *mPrams = [NSMutableDictionary dictionary];
    // 截取字符串的参数部分
    NSString *pramsString = [self substringFromIndex:range.location + 1];
    //判断参数是单个还是多个
    if ([pramsString containsString:@"&"]) {
        // 通过字符串的分割 得到参数数组
        NSArray *urlComponents = [pramsString componentsSeparatedByString:@"&"];
        for (NSString *keyValuepair in urlComponents) {
            //分割字符串keyValuepair 得到包含key value的数组
            NSArray *pairComponents = [keyValuepair componentsSeparatedByString:@"="];
            // key
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            // value
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // key Value 不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            id existValue = [mPrams valueForKey:key];
            
            if (existValue != nil) {
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [mPrams setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [mPrams setValue:@[existValue, value] forKey:key];
                }
                
                
            }else {
                // 设置值
                [mPrams setValue:value forKey:key];
                
            }
        }
        
    }else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [pramsString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [mPrams setValue:value forKey:key];
        
    }
    
    return mPrams;
    
}

- (NSString *)getTimeStampString {
    //时间戳转时间的方法:
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    if ([self containsString:@"-"]) {
        [formatter setDateFormat:@"yyyy-MM-dd"];
    }else if ([self containsString:@"/"]) {
        [formatter setDateFormat:@"yyyy/MM/dd"];
    }else if ([self containsString:@"."]) {
        [formatter setDateFormat:@"yyyy.MM.dd"];
        
    }
    NSDate *date = [formatter dateFromString:self];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    
    return timeSp;
}

- (NSArray *)jsonStringToArray {
    if (self) {
        id tmp = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        
        if (tmp) {
            if ([tmp isKindOfClass:[NSArray class]]) {
                
                return tmp;
                
            } else if([tmp isKindOfClass:[NSString class]]
                      || [tmp isKindOfClass:[NSDictionary class]]) {
                
                return [NSArray arrayWithObject:tmp];
                
            } else {
                return nil;
            }
        } else {
            return nil;
        }
        
    } else {
        return nil;
    }
    
}


- (BOOL)isSpaceString:(NSString *)string {
    NSRange range = [string rangeOfString:@" "];
    
    if (range.location != NSNotFound) {
        
        return YES;
    }else {
        return NO;
    }
    
}

@end
